package com.flyme.module.base.provider.nuonuo;

import cn.hutool.core.date.DateUtil;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONUtil;
import com.flyme.module.base.client.entity.SysInvoice;
import com.flyme.module.base.provider.nuonuo.bean.PrivateData;
import com.flyme.module.base.provider.nuonuo.bean.PublicData;
import com.flyme.module.base.provider.nuonuo.bean.RequestMode;
import com.flyme.module.base.provider.nuonuo.expetion.OpensnsException;
import com.flyme.module.base.provider.nuonuo.service.OpenApiV1;
import com.flyme.module.base.provider.nuonuo.utils.StateData;
import com.flyme.module.base.provider.nuonuo.utils.ValidataUtil;
import com.flyme.module.base.provider.service.SysConfigService;
import org.apache.http.client.HttpClient;
import org.springframework.beans.factory.annotation.Autowired;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class GetInvoice {

    //测试路径
    final static String SendUrl = "https://nnfpdev.jss.com.cn/shop/buyer/allow/cxfKp/cxfServerKpOrderSync.action";
    //正式路径
    final static String SendUrlTrue = "https://nnfp.jss.com.cn/shop/buyer/allow/cxfKp/cxfServerKpOrderSync.action";
    //身份认证
    final static String identity = "A0138BA45284F9C8E711331BE87CA31AF99ED42C73D198F5";
    //开票人
    final static String clerk = "余泳";
    //销方电话
    final static String salephone = "0755-28280321";
    //销方地址
    final static String saleaddress = "深圳市前海深港合作前湾一路1号A栋201室";
    //销方税号
    final static String saletaxnum = "91440300MA5EX93G31";
    @Autowired
    private SysConfigService sysconfigService;

    public static String getInvoice(SysInvoice invoice, String orderNo) {
        String fpqqlsh = "";
        InvoiceData invoiceData = new InvoiceData();
        invoiceData.setIdentity(identity);
        InvoiceOrder invoiceOrder = new InvoiceOrder();
        invoiceOrder.setOrderno(orderNo);
        invoiceOrder.setSaletaxnum(saletaxnum);
        invoiceOrder.setSaleaddress(saleaddress);
        invoiceOrder.setSalephone(salephone);
        invoiceOrder.setClerk(clerk);
        invoiceOrder.setInvoicedate(String.valueOf(DateUtil.date()));
        invoiceOrder.setTsfs("2");
        invoiceOrder.setEmail(invoice.getEmail());
        invoiceOrder.setKptype("1");
        invoiceOrder.setAddress(invoice.getEnterpriseAddress());
        invoiceOrder.setPhone(invoice.getTelephone());
        invoiceOrder.setTaxnum(invoice.getCreditCode());
        invoiceOrder.setBuyername(invoice.getInvoiceTitle());
        invoiceOrder.setAccount(invoice.getBankNo());
        if (invoice.getEinvoice().equals("1")) {//电子发票
            invoiceOrder.setInvoiceLine("p");
        } else {//纸质发票
            invoiceOrder.setTsfs("1");
            if (invoice.getInvoiceType().equals(1)) {//个人发票
                invoiceOrder.setInvoiceLine("c");
            } else {//企业发票
                invoiceOrder.setInvoiceLine("c");
                if (invoice.getInvoiceKind().equals(2)) {
                    invoiceOrder.setInvoiceLine("s");
                }
            }
        }
        List<Detail> detailList = new ArrayList();
        Detail detail = new Detail();
        detail.setGoodsname("培训费");
        detail.setHsbz("1");
        detail.setNum("1");
        detail.setUnit("1");
        detail.setSpec("1");
        detail.setPrice(String.valueOf(invoice.getInvoiceAmount()));
        detail.setSpbm("307020102");
        detail.setFphxz("0");
        detail.setTaxrate("0.06");
        detail.setYhzcbs("0");
        detail.setZzstsgl("22222");
        detail.setLslbs("");
        detailList.add(detail);
        invoiceOrder.setDetail(detailList);
        invoiceData.setOrder(invoiceOrder);
        List<InvoiceData> list=new ArrayList<>();
        list.add(invoiceData);
        String order1 = JSONUtil.toJsonStr(list);
        order1 = order1.substring(1, order1.length() - 1);
        order1 = DESDZFP.encrypt(order1);
        HttpClient httpclient = null;

        HashMap<String, Object> paramMap = new HashMap<>();
        paramMap.put("order", order1);
        String result = HttpUtil.post(SendUrlTrue, paramMap);
        Map<String, Object> data = JSONUtil.toBean(JSONUtil.parseObj(result), Map.class, true);

        if (data.get("status").equals("0000")) {
            fpqqlsh = data.get("fpqqlsh").toString();
        }
        return fpqqlsh;
    }

    // 定义请求头数据
    private static Map<String, String> getHeaders(String token) {
        Map<String, String> headers = new HashMap<String, String>();
        headers.put("appKey", StateData.app_key); // 用户申请的appkey
        headers.put("accessToken", token); // 用户Oauth登录后得到的令牌accessToken
        headers.put("compress", StateData.app_compressType);// 压缩方式：提供GZIP 置空“”不压缩
        headers.put("signMethod", StateData.app_signType); // 加密方式：提供AES/AES，不可为空
        headers.put("dataType", StateData.app_dataType); // 数据请求格式： JSON/XML
        headers.put("appRate", StateData.app_rate); // app并发请求数 ，平台默认10如需升级请联系开放平台
        headers.put("userTax", StateData.user_Tax); // ISV下商家需要填写当前商户税号，普通商家模式用户可以不填写此值
        headers.put("Content-Type", StateData.contentType); // http发送模式
        return headers;
    }

    // 定义请求体中的公共数据
    private static PublicData getPublicData(String method) {
        PublicData pdData = new PublicData();
        pdData.setVersion(StateData.app_apiVersion); // API版本
        pdData.setTimestamp(String.valueOf(System.currentTimeMillis()));
        pdData.setMethod(method);// API名称
        return pdData;
    }

    private static RequestMode getRequestMode(PublicData pdata, PrivateData<Object> pvData) {
        RequestMode requestMode = new RequestMode();
        requestMode.setPrivate(pvData);
        requestMode.setPublic(pdata);
        return requestMode;
    }

    /**
     * 根据企业简称查询
     */
    public static List<Map> selectByName(String companyName, String token) {
        List<Map> resultMap = new ArrayList<>();
        Map<String, String> headers = getHeaders(token);
        PublicData pdData = getPublicData("nuonuo.speedBilling.prefixQuery");
        PrivateData<Object> pvData = new PrivateData<Object>();
        List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("q", companyName);
        list.add(map);
        pvData.setServicedata(list);
        RequestMode requestMode = getRequestMode(pdData, pvData);
        OpenApiV1 sdk = new OpenApiV1();
        try {
            String result = sdk.handle(StateData.url, headers, requestMode);
            if (!ValidataUtil.isEmpty(result)) {
                System.out.println("服务端的响应：" + result);
            }
            Map reMap = JSONUtil.toBean(result, Map.class);
            if(!"S0000".equals(reMap.get("code"))){
                return resultMap;
            }
            //resultMap= JSONUtil.toList(JSONUtil.parseArray(result),Map.class);
            System.out.println("内容：" + reMap.get("result"));
            resultMap= JSONUtil.toList(JSONUtil.parseArray(reMap.get("result")),Map.class);
            /*if (resultMap.size() > 0) {
                for (Map<String, Object> data : resultMap) {
                    Map<String, Object> map2 = selectByName2(String.valueOf(data.get("code")), token);
                    Map<String, Object> kpMap = (Map<String, Object>) map2.get("result");
                    data.put("kpCode", kpMap.get("kpCode"));
                    data.put("systype", kpMap.get("systype"));
                }
            }*/
        } catch (OpensnsException e) {
            System.out.printf("Request failed 【" + e.getErrorCode() + ":" + e.getMessage() + "】");
            e.printStackTrace();
        }
        return resultMap;
    }

    /**
     * 根据企业开票码获取税号等
     */
    public static Map<String, Object> selectByName2(String kCode, String token) {
        Map<String, Object> resultMap = null;
        Map<String, String> headers = getHeaders(token);
        PublicData pdData = getPublicData("nuonuo.speedBilling.queryNameAndTaxByCode");
        PrivateData<Object> pvData = new PrivateData<Object>();
        List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("code", kCode);
        list.add(map);
        pvData.setServicedata(list);
        RequestMode requestMode = getRequestMode(pdData, pvData);
        OpenApiV1 sdk = new OpenApiV1();
        try {
            String result = sdk.handle(StateData.url, headers, requestMode);
            resultMap = JSONUtil.toBean(JSONUtil.parseObj(result),Map.class,true);
        } catch (OpensnsException e) {
            System.out.printf("Request failed 【" + e.getErrorCode() + ":" + e.getMessage() + "】");
            e.printStackTrace();
        }
        return resultMap;
    }


    public static void main(String[] args) {
        Map<String, Object> map = selectByName2("5TECVW", "39d0391a7e64cbfdff1a360yr4ldtxss");
        System.out.println(map);
    }

}
